﻿using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using LitJson;

namespace MyWcfRestLib.Files
{
    abstract class FileOpParams
    {
        public const string RootKey = "root";
        public static readonly char[] InvalidFileNameChars = Path.GetInvalidFileNameChars();

        public JsonData QueryParams { get; private set; }

        /// <summary>
        /// Parses the parameters.
        /// parse the request query string first, if failed, use body as JSON data.
        /// </summary>
        /// <param name="requestQueryParams">The request query params.</param>
        /// <param name="requestBody">The request body.</param>
        /// <returns></returns>
        public static JsonData ParseParameters(NameValueCollection requestQueryParams, Stream requestBody = null)
        {
            JsonData parsedData = null;

            // Try retrieve parameters from query string at first. If failed, use Body as JSON parameters
            if (null != requestQueryParams && requestQueryParams.Count > 0)
            {
                parsedData = new JsonData();
                foreach (var key in requestQueryParams.AllKeys)
                {
                    parsedData[key] = requestQueryParams[key];
                }
            }
            else
            {
                if (null != requestBody)
                {
                    StreamReader streamRead = new StreamReader(requestBody, System.Text.Encoding.UTF8);

                    char[] buffer = new char[256];
                    int charReads = streamRead.Read(buffer, 0, 256);
                    string requestContent = new string(buffer, 0, charReads);
                    parsedData = JsonMapper.ToObject(requestContent);
                }
            }

            return parsedData;
        }

        public FileOpParams(string basePath, NameValueCollection requestQueryParams, Stream requestBody = null)
        {
            Debug.Assert(null != requestQueryParams);

            QueryParams = ParseParameters(requestQueryParams, requestBody);

            BasePath = basePath;

            // Fix root path string
            DeviceRoot = (string)QueryParams[RootKey];
            if (null != DeviceRoot)
            {
                DeviceRoot = DeviceRoot.Trim(InvalidFileNameChars);
            }

        }

        //public FileOpParams(string basePath, JsonData requestQueryParams)

        public string DeviceRoot { get; protected set; }

        public string BasePath { get; private set; }

        abstract public bool IsValid { get; }
    }
}
